# -*- coding:utf-8 -*-

import logging

from . import api
from iHome import db
from iHome.models import User
from iHome.utils import constants
from iHome.utils.captcha.pic_store import pic_store
from iHome.utils.constants import QINIU_DOMIN_PREFIX
from iHome.utils.response_code import RET
from iHome.utils.commons import login_required
from flask import g, jsonify, current_app, request


@api.route('/user')
@login_required
def get_user_info():
    """获取用户信息"""
    user_id = g.user_id
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据错误")

    if not user:
        return jsonify(errno=RET.USERERR, errmsg="用户不存在")

    avatar_url = None
    if user.avatar_url:
        avatar_url = QINIU_DOMIN_PREFIX + user.avatar_url
    resp_dict = {
        "name": user.name,
        "avatar_url": avatar_url,
        "mobile": user.mobile
    }
    return jsonify(errno=RET.OK, errmsg='OK', data=resp_dict)


@api.route("/user/avatar", methods=["POST"])
@login_required
def set_user_avatar():
    """上传头像功能"""
    user_id = g.user_id
    # user_id = session.get("user_id")
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    avatar = request.files.get("avatar")
    try:
        avatar_data = avatar.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="读取图片数据异常")
    if not avatar_data:
        return jsonify(errno=RET.NODATA, errmsg="图片二进制数据为空")

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    #  借助封装好的pic_store方法将图片数据上传到七牛云
    try:
        url = pic_store(avatar_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片到七牛云异常")

    # 将图片名字保存到用户对象上
    if url:
        user.avatar_url = url
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="保存用户数据查询错误")

    # 将完整的图片url组织好，并返回
    avatar_url = constants.QINIU_DOMIN_PREFIX + url

    data = {
        "avatar_url": avatar_url
    }
    return jsonify(errno=RET.OK, errmsg="上传图片到七牛云成功", data=data)


@api.route('/user/auth', methods=['POST'])
@login_required
def set_auth():
    """实名认证"""
    # 1.获取服务器数据并判断
    json_dict = request.get_json()
    real_name = json_dict['real_name']
    id_card = json_dict['id_card']
    if not all([real_name, id_card]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 2.获取当前用户的模型并更新认证信息
    user_id = g.user_id
    try:
        User.query.filter_by(id=user_id).update({'real_name': real_name, 'id_card': id_card})
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='认证信息保存失败')
    else:
        return jsonify(errno=RET.OK, errmsg='认证信息保存成功')


@api.route('/user/auth')
@login_required
def get_auth():
    """获取用户实名认证信息"""
    user_id = g.user_id
    try:
        user = User.query.filter_by(id=user_id).first()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    # 如果用户不存在
    if user is None:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户不存在')

    return jsonify(errno=RET.OK, errmsg='OK', data=user.to_auth_info())


@api.route('/user/name', methods=["POST"])
@login_required
def modify_username():
    name = request.json.get("name", None)
    if not name:
        return jsonify(errno=RET.PARAMERR, errmsg="修改用户名参数不足")
    user_id = g.user_id
    try:
        user = User.query.get(user_id)
        user.name = name
        db.session.commit()
    except Exception as err:
        current_app.logger.error(err)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="更新数据出错")
    return jsonify(errno=RET.OK, errmsg="修改成功")
